<?php

/**
 * This is the model class for table "temper_ext_jours".
 *
 * The followings are the available columns in table 'temper_ext_jours':
 * @property string $dte
 * @property string $tmoy
 * @property string $tmin
 * @property string $tmax
 * @property string $tnb
 */
class TemperExtJour extends CActiveRecord {

    // Champs calculés
    public $dteGroup = null;

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return TemperExtJour the static model class
     */
    public static function model($className = __CLASS__) {
	  return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
	  return 'mesures_temperext_jours';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
	  // NOTE: you should only define rules for those attributes that
	  // will receive user inputs.
	  return array(
		array('dte', 'required'),
		array('tmoy, tmin, tmax, tnb', 'safe'),
		// The following rule is used by search().
		// Please remove those attributes that should not be searched.
		array('dte, tmoy, tmin, tmax, tnb', 'safe', 'on' => 'search'),
	  );
    }

    /**
     * @return array relational rules.
     */
    /*
      public function relations() {
      // NOTE: you may need to adjust the relation name and the related
      // class name for the relations automatically generated below.
      return array(
      );
      }
     */

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
	  return array(
		'dte' => 'Date',
		'tmoy' => 'Temp moyenne',
		'tmin' => 'Temp mini',
		'tmax' => 'Temp maxi',
		'tnb' => 'Nb de relevés',
	  );
    }

    
    
    
    /*
     * Enregistrement des données journalières
     * 
     * @param $dte date date à calculer
     */

    public function getParJour($dte) {
	  
	  // Récupération de la moyenne journalière
	  $criteria = new CDbCriteria();
	  $criteria->select = 'AVG(temperature) AS tmoy, MIN(temperature) AS tmin, MAX(temperature) AS tmax, COUNT(temperature) AS tnb ';
	  $criteria->condition = "dte LIKE :dte";
	  $criteria->group = 'SUBSTR(dte, 1,10)';
	  $criteria->params = array('dte' => $dte.'%');


	  $result = TemperExtReleve::model()->findAll($criteria);

	  if(count($result) != 1){
		Yii::log('Données des relevés invalides pour le '.$dte, 'warning', 'mesures.TemperExtJour');

	  }
	  else {
	
		// Récupération des valeurs
		$this->setAttributes(array(
		    'dte' => $dte,
		    'tmoy' => $result[0]->tmoy,
		    'tmin' => $result[0]->tmin,
		    'tmax' => $result[0]->tmax,
		    'tnb' => $result[0]->tnb,
			)
		);

		// Aout ou mise à jour du jour
		$this->save();
	  }
    }

    
    
    
    /*
     * Génération des graphiques
     * 
     */

    public static function getGraphJournalier() {
	  $graphOptions = array(
		'title' => array('text' => 'Températures journalières'),
	  );
	  $graphData = TemperExtJour::getGraphData(array('groupby' => 'dte', 'duree' => '3 MONTH'));
	  return array_merge($graphOptions, $graphData);
    }

    public static function getGraphMensuel() {
	  $graphOptions = array(
		'title' => array('text' => 'Températures menuselles'),
	  );
	  $graphData = TemperExtJour::getGraphData(array('groupby' => 'SUBSTR(dte, 1, 7)', 'duree' => '2 YEAR'));
	  return array_merge($graphOptions, $graphData);
    }

    public static function getGraphAnnuel() {
	  $graphOptions = array(
		'title' => array('text' => 'Températures annuelles'),
	  );
	  $graphData = TemperExtJour::getGraphData(array('groupby' => "CONCAT(SUBSTR(dte, 1, 4) , '-06-01')", 'duree' => '10 YEAR'));
	  return array_merge($graphOptions, $graphData);
    }

    /*
     * Récupération des données de température pour les graphs
     * @options array : liste des paramètres (groupby, duree)
     * @return array
     */

    private static function getGraphData($options = array()) {
	  $criteria = new CDbCriteria();
	  $criteria->select = $options['groupby'] . ' AS dteGroup, AVG(tmoy) AS tmoy, AVG(tmax) AS tmax, AVG(tmin) AS tmin ';
	  $criteria->condition = "dte >= NOW() - INTERVAL " . $options['duree'];
	  $criteria->group = 'dteGroup';
	  $criteria->order = 'dteGroup';
	  //$criteria->params = array('duree' => $options['duree']);

	  $result = TemperExtJour::model()->findAll($criteria);

	  //$hp = array();
	  $avg = array();
	  $minmax = array();

	  foreach ($result as $rs) {

		$dte = 1000 * strtotime($rs->dteGroup);
		$dte = (string) $dte;

		$avg[] = array((float) $dte, round($rs->tmoy, 1));
		$minmax[] = array((float) $dte, round($rs->tmin, 0), round($rs->tmax, 0));
	  }

	  $graph = array(
		'yAxisTitre' => '°C',
		'xAxis' => array('type' => 'datetime'),
		'series' => array(
		    array(
			  'name' => 'Température',
			  'data' => $avg,
			  'zIndex' => 1,
			  'color' => '#058DC7',
			  'marker' => array(
				'fillColor' => 'white',
				'lineWidth' => 2,
				'lineColor' => '#058DC7'
			  ),
		    ),
		    array(
			  'name' => 'Min - Max',
			  'type' => 'arearange',
			  'data' => $minmax,
			  'lineWidth' => 0,
			  'linkedTo' => ':previous',
			  'color' => '#B3DBEE',
			  'fillOpacity' => 0.5,
			  'zIndex' => 0
		    ),
		),
	  );
	  return $graph;
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    /*
      public function search()
      {
      // Warning: Please modify the following code to remove attributes that
      // should not be searched.

      $criteria=new CDbCriteria;

      $criteria->compare('dte',$this->dte,true);
      $criteria->compare('tmoy',$this->tmoy,true);
      $criteria->compare('tmin',$this->tmin,true);
      $criteria->compare('tmax',$this->tmax,true);
      $criteria->compare('tnb',$this->tnb,true);

      return new CActiveDataProvider($this, array(
      'criteria'=>$criteria,
      ));
      }
     * 
     */
}